import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Upload,
  message,
  Popconfirm,
  Tag,
  Image,
  Typography,
  Row,
  Col,
  Statistic
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  UploadOutlined,
  EyeOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { productAPI } from '../../services/api';

const { Title } = Typography;
const { TextArea } = Input;
const { Option } = Select;

const ProductManagement = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [stats, setStats] = useState({
    totalProducts: 0,
    totalValue: 0,
    lowStockCount: 0
  });

  // 商品分类选项
  const categoryOptions = [
    '电子产品',
    '服装',
    '家居',
    '图书',
    '运动',
    '美妆',
    '食品',
    '其他'
  ];

  // 加载商品列表
  const loadProducts = async (page = 1, pageSize = 10, keyword = '') => {
    setLoading(true);
    try {
      let response;
      if (keyword.trim()) {
        response = await productAPI.search(keyword);
        // 搜索结果转换为分页格式
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedData = response.slice(startIndex, endIndex);
        
        setProducts(paginatedData);
        setPagination(prev => ({
          ...prev,
          current: page,
          total: response.length
        }));
      } else {
        response = await productAPI.getAll(page - 1, pageSize);
        if (response?.content) {
          setProducts(response.content);
          setPagination(prev => ({
            ...prev,
            current: page,
            total: response.totalElements
          }));
        } else if (Array.isArray(response)) {
          setProducts(response);
          setPagination(prev => ({
            ...prev,
            current: page,
            total: response.length
          }));
        }
      }
    } catch (error) {
      console.error('加载商品列表失败:', error);
      message.error('加载商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载统计数据
  const loadStats = async () => {
    try {
      const response = await productAPI.getStats();
      setStats({
        totalProducts: response?.totalProducts || 0,
        totalValue: response?.totalValue || 0,
        lowStockCount: response?.lowStockCount || 0
      });
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 搜索商品
  const handleSearch = (value) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
    loadProducts(1, pagination.pageSize, value);
  };

  // 分页变化
  const handleTableChange = (paginationConfig) => {
    setPagination(paginationConfig);
    loadProducts(paginationConfig.current, paginationConfig.pageSize, searchText);
  };

  // 打开新增/编辑模态框
  const handleOpenModal = (product = null) => {
    setEditingProduct(product);
    setModalVisible(true);
    if (product) {
      form.setFieldsValue({
        ...product,
        tags: product.tags ? product.tags.join(',') : ''
      });
    } else {
      form.resetFields();
    }
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingProduct(null);
    form.resetFields();
  };

  // 保存商品
  const handleSaveProduct = async (values) => {
    try {
      const productData = {
    ...values,
    tags: values.tags ? values.tags.split(',').map(tag => tag.trim()).filter(tag => tag) : []
  };

      if (editingProduct) {
        await productAPI.update(editingProduct.id, productData);
        message.success('商品更新成功');
      } else {
        await productAPI.create(productData);
        message.success('商品创建成功');
      }

      handleCloseModal();
      loadProducts(pagination.current, pagination.pageSize, searchText);
      loadStats();
    } catch (error) {
      console.error('保存商品失败:', error);
      message.error('保存商品失败');
    }
  };

  // 删除商品
  const handleDeleteProduct = async (id) => {
    try {
      await productAPI.delete(id);
      message.success('商品删除成功');
      loadProducts(pagination.current, pagination.pageSize, searchText);
      loadStats();
    } catch (error) {
      console.error('删除商品失败:', error);
      message.error('删除商品失败');
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    loadProducts(pagination.current, pagination.pageSize, searchText);
    loadStats();
  };

  // 初始加载
  useEffect(() => {
    loadProducts();
    loadStats();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '商品图片',
      dataIndex: 'imageUrl',
      key: 'imageUrl',
      width: 100,
      render: (imageUrl, record) => (
        <Image
          width={60}
          height={60}
          src={imageUrl || '/api/placeholder/60/60'}
          alt={record.name}
          style={{ objectFit: 'cover', borderRadius: '4px' }}
          fallback="/api/placeholder/60/60"
        />
      )
    },
    {
      title: '商品名称',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (text) => <span title={text}>{text}</span>
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (category) => (
        <Tag color="blue">{category || '未分类'}</Tag>
      )
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (price) => `¥${parseFloat(price || 0).toFixed(2)}`,
      sorter: (a, b) => (a.price || 0) - (b.price || 0)
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 80,
      render: (stock) => (
        <Tag color={stock > 10 ? 'green' : stock > 0 ? 'orange' : 'red'}>
          {stock || 0}
        </Tag>
      ),
      sorter: (a, b) => (a.stock || 0) - (b.stock || 0)
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      key: 'viewCount',
      width: 100,
      render: (count) => (
        <span>
          <EyeOutlined /> {count || 0}
        </span>
      ),
      sorter: (a, b) => (a.viewCount || 0) - (b.viewCount || 0)
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status, record) => {
        const stock = record.stock || 0;
        if (stock === 0) {
          return <Tag color="red">缺货</Tag>;
        } else if (stock <= 10) {
          return <Tag color="orange">库存不足</Tag>;
        } else {
          return <Tag color="green">正常</Tag>;
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleOpenModal(record)}
            size="small"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个商品吗？"
            onConfirm={() => handleDeleteProduct(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div className="product-management">
      {/* 页面头部 */}
      <div className="page-header">
        <Title level={2}>商品管理</Title>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic
              title="商品总数"
              value={stats.totalProducts}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic
              title="总价值"
              value={stats.totalValue}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic
              title="库存不足"
              value={stats.lowStockCount}
              valueStyle={{ color: '#ff4d4f' }}
              suffix="件"
            />
          </Card>
        </Col>
      </Row>

      {/* 操作工具栏 */}
      <Card className="toolbar-card">
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <Input.Search
                placeholder="搜索商品名称或分类"
                allowClear
                style={{ width: 300 }}
                onSearch={handleSearch}
                enterButton={<SearchOutlined />}
              />
            </Space>
          </Col>
          <Col>
            <Space>
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
              >
                刷新
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleOpenModal()}
              >
                新增商品
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 商品表格 */}
      <Card className="table-card">
        <Table
          columns={columns}
          dataSource={products}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
          onChange={handleTableChange}
          rowKey="id"
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 新增/编辑商品模态框 */}
      <Modal
        title={editingProduct ? '编辑商品' : '新增商品'}
        open={modalVisible}
        onCancel={handleCloseModal}
        footer={null}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveProduct}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="商品名称"
                rules={[{ required: true, message: '请输入商品名称' }]}
              >
                <Input placeholder="请输入商品名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="商品分类"
                rules={[{ required: true, message: '请选择商品分类' }]}
              >
                <Select placeholder="请选择商品分类">
                  {categoryOptions.map(category => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="price"
                label="商品价格"
                rules={[{ required: true, message: '请输入商品价格' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入商品价格"
                  min={0}
                  precision={2}
                  addonBefore="¥"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="stock"
                label="库存数量"
                rules={[{ required: true, message: '请输入库存数量' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入库存数量"
                  min={0}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="商品描述"
          >
            <TextArea
              rows={4}
              placeholder="请输入商品描述"
            />
          </Form.Item>

          <Form.Item
            name="imageUrl"
            label="商品图片URL"
          >
            <Input placeholder="请输入商品图片URL" />
          </Form.Item>

          <Form.Item
            name="tags"
            label="商品标签"
            extra="多个标签用逗号分隔"
          >
            <Input placeholder="例如：热销,推荐,新品" />
          </Form.Item>

          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={handleCloseModal}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingProduct ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductManagement;